package com.arraymasterx.algorithm.sort;

import com.arraymasterx.config.AlgorithmConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class QuickSort implements SortAlgorithm {

    private final AlgorithmConfig algorithmConfig;

    @Autowired
    public QuickSort(AlgorithmConfig algorithmConfig) {
        this.algorithmConfig = algorithmConfig;
    }

    @Override
    public int[] sort(int[] array) {
        validateInput(array);
        quickSort(array, 0, array.length - 1);
        return array;
    }

    private void quickSort(int[] array, int low, int high) {
        if (low < high) {
            int pi = partition(array, low, high);
            quickSort(array, low, pi - 1);
            quickSort(array, pi + 1, high);
        }
    }

    private int partition(int[] array, int low, int high) {
        int pivot = array[high];
        int i = low - 1;

        for (int j = low; j < high; j++) {
            if (array[j] < pivot) {
                i++;
                swap(array, i, j);
            }
        }
        swap(array, i + 1, high);
        return i + 1;
    }

    private void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    private void validateInput(int[] array) {
        if (array == null) {
            throw new IllegalArgumentException("Input array cannot be null");
        }

        if (array.length > algorithmConfig.getSort().getMaxElements()) {
            throw new IllegalArgumentException(
                    "Array size exceeds maximum allowed size: " + algorithmConfig.getSort().getMaxElements());
        }
    }
}